<template>
  <div :class="stateClass" class="content-wrap">
    <div
      v-show="
        (isLastOne && keyWordList?.length) ||
        error ||
        message?.length ||
        (chat.nodeType === ENodeType.MULTI_NODE &&
          chat.answerState >= EAnswerState.ANSWERING &&
          multiAnswerContent?.length)
      "
      :class="stateClass"
      class="content-innerWrap"
    >
      <template v-if="error">
        <div class="err-icon-wrap" @click="$emit('resend-chat', chat)">
          <img
            src="https://zuiyouliao.oss-cn-beijing.aliyuncs.com/ZYL-HQ/static/images/ic_recycle_white.png"
            mode="aspectFill"
            alt=""
            class="err-icon"
          />
        </div>
        <div class="message-content error-message" :class="stateClass">发送失败，请重新发送</div>
      </template>
      <KeywordList v-if="isLastOne && keyWordList?.length" v-bind="chat" />

      <!-- <div v-if="isLastOne && paperList?.length" class="mg-24 paper-list answer-border">
        <p><strong>检索到相关文献如下：</strong></p>
        <ol>
          <li v-for="paper in paperList" :key="paper.paperId">
            {{ paper.title }}
          </li>
          ...
        </ol>
        <p>
          上述论文是问题相关的前{{
            paperList.length
          }}篇，如果需要查看详细论文情况，请点击【查看文献】按钮，查看论文详情
        </p>
      </div> -->

      <!-- isAnswer -->
      <div class="message-content answer answer-border">
        <!-- <div v-if="
          !paperList?.length &&
          searchType === 1 &&
          isLastOne &&
          answerState &&
          EAnswerState.PAPER_FOUND < answerState &&
          chat.queryType === 1
        " class="mg-24">
          <strong>未找到相关文献，以下内容由AI直接作答</strong>
          <p></p>
        </div>        -->
        <!-- 多节点循环 -->
        <template v-if="chat.nodeType === ENodeType.MULTI_NODE && chat.type !== 'sent'">
          <template
            v-if="
              chat.replyState && (chat.replyState === 2 || chat.replyState === 3) && chat.message
            "
          >
            {{ chat.message }}
          </template>
          <a-timeline-item
            class="timeline-item"
            v-for="(nodeItem, index) in multiAnswerContent"
            :key="nodeItem.id"
            :class="{
              'last-timeline-item':
                index === multiAnswerContent.length - 1 &&
                (chat.answerState === EAnswerState.FINISH_ANSWER || chat.replyState)
            }"
          >
            <template #dot><i class="timeline_dot"></i></template>
            <MarkdownParser
              @changePage="chatPageChange"
              v-bind="{
                ...nodeItem,
                message: nodeItem.answerContent || nodeItem.message,
                isLastOne: chat.isLastOne,
                isAnswering: chat.isAnswering,
                replyState: chat.replyState,
                id: chat.id,
                answerId: chat.answerId,
                subIndex: index
              }"
              :hasCursor="
                index === multiAnswerContent.length - 1 && chat.isLastOne && !chat.replyState
              "
              :isMultiNode="isMultiNode"
            />
          </a-timeline-item>
        </template>
        <!-- 单节点 -->
        <template v-else-if="!isMultiNode || chat.replyState">
          <a-timeline-item
            v-if="
              isAnswer &&
              answerState !== EAnswerState.SEARCHING &&
              chat.message?.replace(/\s+/g, '')?.length
            "
            class="timeline-item last-timeline-item"
          >
            <template #dot><i class="timeline_dot"></i></template>
            <MarkdownParser
              @changePage="chatPageChange"
              v-bind="chat"
              :isMultiNode="isMultiNode"
            />
          </a-timeline-item>
        </template>

        <!-- <a-timeline-item :class.prop="'ant-timeline-item-last'"><slot></slot></a-timeline-item> -->

        <!-- <div @click="pageIndexClick(1)">1</div> -->
        <div
          v-if="
            chat.queryType === 2 &&
            chat.pdfPageIdList &&
            chat.pdfPageIdList?.length > 0 &&
            chat.type === 'received'
          "
        >
          <span class="page-index-title">页码：</span>
          <div
            v-for="page in chat.pdfPageIdList"
            :key="page"
            class="page-index"
            @click="pageIndexClick(page)"
          >
            <span>{{ page }}</span>
          </div>
        </div>
        <div
          v-if="
            chat.replyState !== 2 &&
            chat.type === 'received' &&
            (!chat?.isFlowing || chat.answerState === EAnswerState.FINISH_ANSWER) &&
            (!chat?.isAnswering || chat.replyState === true) &&
            chat.replyState !== 0
          "
          class="paper-list-button"
        >
          <div class="ic_copy icon" @click="copyText(chat)"></div>
          <div
            v-if="isLastOne && (chat.replyState === 1 || chat.replyState)"
            class="ic_refresh icon"
            @click="$emit('resend-chat', chat)"
          ></div>
          <!-- @todo inject isSelecting进来，隐藏这个 -->
          <div
            class="ic_share icon"
            @click.stop="$emit('share-chat', chat)"
          ></div>
          <div
            class="icon"
            :class="chat.hasSupport === 1 ? 'ic_upvote_active' : 'ic_upvote'"
            @click="$emit('vote-change', chat, chat.hasSupport === 1 ? 0 : 1)"
          ></div>
          <div
            class="icon"
            :class="chat.hasSupport === 2 ? 'ic_downvote_active' : 'ic_downvote'"
            @click="$emit('vote-change', chat, chat.hasSupport === 2 ? 0 : 2)"
          ></div>
          <a
            v-if="resourceIds?.length && chat.queryType === 1"
            @click="chat.opened ? $emit('close-reference') : $emit('show-detail', chat)"
            >{{ chat.opened ? '收回' : '查看文献' }}</a
          >
          <!-- <a v-if="searchType !== 1 && !isLoading && chat.queryType === 1" @click="$emit('strong-ask', chat)">在知识库中搜索</a> -->
        </div>
      </div>

      <!-- isQuestion -->
      <pre v-if="isQuestion && !error" :class="stateClass" class="message-content">{{
        questionContent
      }}</pre>
    </div>
    <div v-if="isAnswer && replyState === 2 && message?.length === 0" class="stopContent">
      数字材料助理工程师已中断回答
    </div>
    <div v-else-if="isAnswer && replyState === 3 && message?.length === 0" class="stopContent">
      数字材料助理工程师响应超时，请重新提问
    </div>
    <div
      v-if="
        isAnswer &&
        !!replyState &&
        isLastOne &&
        replyState !== 2 &&
        replyState !== 3 &&
        (!chat?.isFlowing ||
          ((chat?.answerState || 0) > EAnswerState.ANSWERING &&
            (chat?.answerState || 0) <= EAnswerState.FINISH_ANSWER))
      "
      class="related-list"
    >
      <div
        v-for="QText in suggestQuestionList"
        :key="QText"
        class="related-item"
        @click="$emit('click-related-item', QText)"
      >
        <span class="text" v-if="QText?.length && replyState != 2">
          {{ QText }}
        </span>
        <!-- <img src="@/static/image/ic_arrow_right.png" mode="aspectFill" alt="" class="icon-arrow" /> -->
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { message as msgHelper } from 'ant-design-vue'
import { type MainItemVo, type Article, EAnswerState, ENodeType } from '@/api/type'
import MarkdownParser from './MarkdownParser.vue'
import { useMessageHook } from './useMessageHook'
import KeywordList from './KeywordList.vue'
import { useClipboard } from '@vueuse/core'
import { useChatBus } from '@/hook/useChatBus'
import { computed } from 'vue'
const bus = useChatBus(() => {})
const { copy } = useClipboard()
const chat = defineProps<MainItemVo>()
const emit = defineEmits<{
  (e: 'strong-ask', _chat: MainItemVo): void
  (e: 'resend-chat', _chat: MainItemVo): void
  (e: 'share-chat', _chat: MainItemVo): void
  (e: 'click-quote-item', _chat: Article): void
  (e: 'click-related-item', _question: string): void
  (e: 'show-detail', _chat: MainItemVo): void
  (e: 'close-reference'): void
  (e: 'vote-change', _chat: MainItemVo, type?: 0 | 1 | 2): void
  (e: 'page-change', index: number, id: string): void
}>()

const { isAnswer, stateClass, isQuestion } = useMessageHook(chat)

const isMultiNode = computed(() => {
  return chat.nodeType === ENodeType.MULTI_NODE
})

const copyText = (chat: MainItemVo) => {
  console.warn(chat,'chat');
  if(isMultiNode && !chat.message && chat?.answerContentList?.length) {
    const copyContent = chat?.answerContentList?.map((c) => c.message).join('')
    copy(copyContent)
    msgHelper.success('复制成功')
    return
  }
  copy(chat.message as string)
  msgHelper.success('复制成功')
}
const chatPageChange = ({ id, index }) => {
  emit('page-change', index, id)
  // console.log('chatPageChange',id,index)
}
const pageIndexClick = (index: number) => {
  console.log('pageIndexClick', index)
  bus.emit('pageIndexClick', index)
  // bus.emit('pageIndexClick', 1)
}

const multiAnswerContent = computed(() => {
  let flowingIndex: number
  if (chat.isFlowing) {
    flowingIndex = chat.answerContentList?.findIndex(
      (c) => c.isFlowing || c.answerState <= EAnswerState.ANSWERING
    )
  }
  if (chat.nodeType !== ENodeType.MULTI_NODE) return []
  if (
    (chat.replyState && !chat?.answerContentList?.length) ||
    (!chat.replyState && chat.answerContent)
  ) {
    const res = chat.answerContent?.split('~~~') || []
    if (chat?.answerContentList?.length) {
      if (chat?.answerContentList?.length >= res.length) {
        return chat?.answerContentList?.filter?.((v, i) => {
          if (!chat.isFlowing) return v.answerState >= EAnswerState.ANSWERING

          return v.answerState >= EAnswerState.ANSWERING && i <= flowingIndex
        })
      }
    }
    return res?.map((c) => ({ answerContent: c, answerState: 5, message: c }))
  }
  return chat?.answerContentList?.filter?.((v, i) => {
    if (!chat.isFlowing) return v.answerState >= EAnswerState.ANSWERING

    return v.answerState >= EAnswerState.ANSWERING
  })
  // return chat.nodeType === ENodeType.MULTI_NODE
  //   ? (chat.replyState && !chat?.answerContentList?.length) ||
  //     (!chat.replyState && chat.answerContent)
  //     ? chat.answerContent
  //         ?.split('~~~')
  //         ?.map((c) => ({ answerContent: c, answerState: 5, message: c }))
  //     : chat?.answerContentList?.filter?.((v, i) => {
  //         if (!chat.isFlowing) return v.answerState === EAnswerState.ANSWERING

  //         return v.answerState === EAnswerState.ANSWERING && i <= flowingIndex
  //       })
  //   : []
})
</script>

<style lang="scss" scoped>
.content-wrap {
  // width: 100%;
  font-size: 14px;

  .error-message {
    font-size: 14px;
    margin-top: 8px;
    margin-bottom: 20px;
  }

  .content-innerWrap {
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-end;
    color: #10121a;
    align-items: center;
    font-size: 14px;
    line-height: 24px;
    max-width: 100%;

    &.answer {
      // background: #f8fafc;
      padding: 0;
      width: 100%;
    }

    .err-icon-wrap {
      cursor: pointer;
      flex: 0;
      display: flex;
      flex-flow: column nowrap;
      justify-content: center;
      align-items: center;
      background-color: #e0445a;
      border-radius: 100%;
      padding: 4px;
      margin-right: 20px;

      .err-icon {
        width: 38px;
        height: 38px;
      }
    }

    .message-content {
      flex: 1;
      font-size: 14px;
      word-break: break-all;
      width: 100%;
      overflow: hidden;

      &.question {
        border-radius: 8px;
        border-top-right-radius: 0;
        background: linear-gradient(107deg, #60a9f6 1%, #2a8bf2 100%);
        padding: 16px 20px;
        color: #fff;
      }

      &.answer {
        // background: #f8fafc;
        width: 100%;
      }

      &.error {
        color: #fff;
        background-color: #e0445a;
      }
      ::selection {
        color: inherit;
        background-color: #bbd6fb;
      }
    }

    .message-content + .question {
      width: unset;
      flex: unset;
    }

    pre.message-content {
      white-space: pre-wrap;
      white-space: -moz-pre-wrap;
      white-space: -pre-wrap;
      white-space: -o-pre-wrap;
      word-wrap: break-word;
    }

    .voice-wrap {
      display: flex;
      flex-flow: column nowrap;
      justify-content: flex-start;
      align-items: flex-end;

      .voice-row {
        display: flex;
        flex-flow: row nowrap;
        justify-content: flex-start;
        align-items: center;
      }

      .voice-content {
        padding: 0 38px;
        flex: 1;
        height: 76px;
        line-height: 76px;
        border-radius: 8px;
        background: #3875f6;
        color: #fff;
        display: flex;
        flex-flow: row nowrap;
        justify-content: flex-end;
        align-items: center;

        &.error {
          color: #fff;
          background: #e0445a;
        }

        .icon-wifi {
          width: 24px;
          height: 24px;
          background: transparent
            url('https://zuiyouliao.oss-cn-beijing.aliyuncs.com/ZYL-HQ/static/images/icon_wifi_white.png')
            no-repeat right 10px center;
          background-size: contain;
          background-position: center center;
          margin-left: 20px;

          &.twinkle {
            animation: twinkle 0.35s alternate infinite;
          }
        }
      }

      .voice-interpret {
        background: #e8e9eb;
        padding: 20px 28px;
        margin-top: 10px;
        border-radius: 8px;
        color: #10121a;
        line-height: 1.5em;
      }
    }

    &.answer {
      display: flex;
      flex-flow: column nowrap;
      justify-content: flex-start;
      align-items: flex-start;
      border-radius: 8px;
      border-top-left-radius: 0;

      &.net-error {
        color: #fff;
        padding: 16px 20px;
        // background-color: #e0445a;

        background: rgba(252, 93, 80, 0.05);
        color: #fc5d50;

        .icon-netErr-wrap {
          display: flex;
          flex-flow: column nowrap;
          justify-content: center;
          align-items: center;

          .icon-netError {
            width: 24px;
            height: 24px;
          }
        }
      }

      .quote-feedback {
        width: 100%;
        background-color: #ffffff;
        box-sizing: border-box;
        color: #333;

        .quote-wrap {
          padding-top: 20px;
          display: flex;
          flex-flow: row wrap;
          justify-content: flex-start;
          align-items: center;

          .quote-item {
            display: flex;
            flex-flow: row nowrap;
            justify-content: flex-start;
            align-items: center;
            height: 56px;
            line-height: 56px;
            border-radius: 56px;
            margin-right: 20px;
            margin-top: 10px;
            margin-bottom: 10px;
            padding: 0 18px;
            border: 1px solid #e5e5e5;
            color: #333333;

            .quote-index {
              width: 24px;
              height: 24px;
              line-height: 24px;
              border-radius: 8px;
              text-align: center;
              background-color: #ebebeb;
              color: #8d9199;
              font-size: 14px;
              margin-right: 10px;
            }

            .quote-img {
              margin-right: 14px;
              width: 24px;
              height: 24px;
              border-radius: 8px;
            }

            .quote-text {
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
        }

        .feedback-wrap {
          display: flex;
          flex-flow: row wrap;
          justify-content: flex-start;
          align-items: center;
          padding: 24px 0 24px 0;

          .feedback-item {
            display: flex;
            flex-flow: row nowrap;
            justify-content: center;
            align-items: center;
            height: 24px;
            line-height: 24px;
            padding: 0 24px;
            background: #f5f6f8;
            border-radius: 28px;
            text-align: center;
            margin-right: 12px;

            .text {
              font-size: 14px;
              font-weight: normal;
              line-height: 36px;
              color: #16191d;
            }

            .icon {
              width: 16px;
              height: 16px;
              background-size: contain;
              background-repeat: no-repeat;
              background-position: center center;
              margin-right: 10px;
              // opacity: 0.5;
            }

            &.upvote {
              &.active {
                .text {
                  color: #3c7bff;
                }
              }

              .icon {
                background-image: url('@/static/image/ic_upvote.png');
                &.active {
                  opacity: 1;
                  background-image: url('@/static/image/ic_upvote_active.png');
                }
              }
            }

            &.downvote {
              &.active {
                .text {
                  color: #f26666;
                }
              }

              .icon {
                &.active {
                  opacity: 1;
                  background-image: url('@/static/image/ic_downvote_active.png');
                }

                background-image: url('@/static/image/ic_downvote.png');
              }
            }
          }
        }
      }
    }
  }
  .stopContent {
    color: #0d1c2e;
    padding: 16px;
  }

  .paper-list {
    background: #f8fafc;
    margin-bottom: 8px;
    padding: 16px 20px;
    width: 100%;
  }

  .paper-list-button {
    margin-top: 8px;
    text-align: right;
    color: #3875f6;
    width: 100%;
    text-align: right;
    display: flex;

    a {
      margin-left: auto;
    }

    .icon {
      width: 20px;
      height: 20px;
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center center;
      margin-right: 16px;
      cursor: pointer;
    }
  }

  .related-list {
    position: relative;
    display: flex;
    flex-flow: column nowrap;
    justify-content: flex-start;
    align-items: stretch;
    // background-color: #fff;
    // border-radius: 8px;
    width: 100%;
    // border-top: 1px solid #DBDEE2;
    margin: 0 20px;
    padding: 12px 0 12px 0;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      bottom: auto;
      right: auto;
      height: 1px;
      width: calc(100% - 35px);
      background-color: #dbdee2;
    }

    .related-item {
      cursor: pointer;
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      justify-content: space-between;
      color: #242733;
      padding: 7px 0px;
      font-size: 14px;
      color: #2a8bf2;

      &:hover {
        background: #f8fafc;
      }

      .text {
        max-width: 95%;
        flex: 1;
        word-break: break-all;
      }

      .icon-arrow {
        width: 20px;
        height: 20px;
      }
    }
  }
}

.text-container {
  .answer {
    width: 100%;
  }
  .page-index-title {
    font-size: 16px;
    font-weight: 500;
  }
  .page-index {
    display: inline-block;
    cursor: pointer;
    color: #2a8bf2;
    margin-right: 5px;
  }
}

.ic_copy {
  background-image: url('@/static/image/ic_copy.png');
}
.ic_copy:hover {
  background-image: url('@/static/image/ic_copy_hover.png');
}

.ic_refresh {
  background-image: url('@/static/image/ic_refresh.png');
}
.ic_refresh:hover {
  background-image: url('@/static/image/ic_refresh_hover.png');
}
.ic_share {
  background-image: url('@/static/image/ic_share.png');
}
.ic_share:hover {
  background-image: url('@/static/image/ic_share_hover.png');
}

.ic_upvote {
  background-image: url('@/static/image/ic_upvote.png');
  margin-right: 20px !important;
}
.ic_upvote_active {
  background-image: url('@/static/image/ic_upvote_hover.png');
  margin-right: 20px !important;
}
.ic_upvote:hover {
  background-image: url('@/static/image/ic_upvote_hover.png');
}
.ic_upvote::after,
.ic_upvote_active::after {
  content: '';
  display: block;
  width: 1px;
  height: 16px;
  background: #dbdee2;
  margin-left: 30px;
  margin-top: 2px;
}

.ic_downvote {
  background-image: url('@/static/image/ic_downvote.png');
}
.ic_downvote_active {
  background-image: url('@/static/image/ic_downvote_hover.png');
}
.ic_downvote:hover {
  background-image: url('@/static/image/ic_downvote_hover.png');
}

.timeline_dot {
  display: inline-block;
  width: 20px;
  height: 20px;
  background: url('@/assets/timeline_dot.png') no-repeat;
  background-size: 100% 100%;
}
.timeline-item {
  &:last-of-type {
    padding-bottom: 0;
  }
  :deep() {
    .ant-timeline-item-head {
      background-color: transparent;
    }
  }
}
.last-timeline-item {
  :deep() {
    .ant-timeline-item-tail {
      display: none;
    }
  }
}
</style>
